import FishMathUtils from "../../engine/utils/FishMathUtils";

const { ccclass, property } = cc._decorator;

@ccclass
export default class CannonManager extends cc.Component {

    public static instance: CannonManager = null;

    @property({ type: cc.Node })
    private view: cc.Node = null;

    @property({ type: [cc.SpriteFrame] })
    private cannonSpriteFrame: Array<cc.SpriteFrame> = []

    public cannonType: number = 1;

    onLoad() {
        CannonManager.instance = this;
        this.node.parent.on(cc.Node.EventType.MOUSE_MOVE, this.onMeMove.bind(this))
        this.refreshCannon();
    }

    private onMeMove(event: cc.Event.EventMouse) {
        let localTouch: cc.Vec2 = this.node.convertToNodeSpaceAR(event.getLocation());
        let rad: number = FishMathUtils.p2pRad(this.view.getPosition(), localTouch)
        let rot: number = FishMathUtils.radiansToDegrees(rad)
        this.view.angle = rot - 90;
    }

    public refreshCannon() {
        this.view.getComponent(cc.Sprite).spriteFrame = this.cannonSpriteFrame[this.cannonType - 1];
    }

    public getCannonPosition() {
        return this.view.getPosition();
    }

    onDestroy() {
        CannonManager.instance = null;
    }

}

